<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" title="申请" width="50%" append-to-body>
      <el-form ref="form" :model="formData" label-width="100" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="申请方式" prop="applyType">
              <el-radio-group v-model="formData.applyType">
                <el-radio :value="1">资产分类</el-radio>
                <el-radio :value="2">资产</el-radio>
                <el-radio :value="3">描述</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.applyType === 1">
          <el-col :span="24">
            <el-form-item label="资产分类" prop="categoryList">
              <div style="width: 100%;">
                <div>
                  <el-button type="primary" link @click="insertCategoryList">添加</el-button>
                </div>
                <vxe-table ref="categoryTableRef" :data="formData.categoryList" width="100%"
                           keep-source>
                  <vxe-column field="categoryId" title="资产分类" :edit-render="regionEditRender">
                    <template #default="{ row }">
                      <category-select v-model="row.categoryId"></category-select>
                    </template>
                  </vxe-column>
                  <vxe-column field="num" title="申请数量">
                    <template #default="{ row }">
                      <el-input v-model="row.num"></el-input>
                    </template>
                  </vxe-column>
                  <vxe-column title="操作" width="100">
                    <template #default="{ row, index }">
                      <el-button link @click="handleDeleteCategory(row, index)">删除</el-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>


            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.applyType === 2">
          <el-col :span="24">
            <el-form-item label="资产" prop="assetList">
              <div style="width: 100%;">
                <choose-table ref="assetTableRef"></choose-table>
              </div>


            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="remark">
          <el-input type="textarea" v-model="formData.remark" placeholder="请输入" />
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="sub">提交</el-button>
          <el-button @click="close">取 消</el-button>
        </el-row>

      </div>
    </el-dialog>

  </div>
</template>

<script setup>

import { VxeUI } from 'vxe-table';
import api from "@/api/asset/apply.js";
import ChooseTable from "@/components/Asset/ChooseTable.vue";
import CategorySelect from "@/components/Asset/CategorySelect.vue";

const emit = defineEmits(['sub']);

const props = defineProps({
  applyType: {
    type: String,
    required: true,
  },
  applyTypeName: {
    type: String,
    required: true,
  }
})

// 是否编辑
const isEdit = ref(false);

const applyDataInit = {
  id: null,
  applyType: props.applyType,
  applyTypeName: props.applyTypeName,
  remark: null,
}

const applyData = reactive({ ...applyDataInit });

const formDataInit = {
  targetUserId: null,
  applyType: 1,
  categoryList: [],
  assetList: [],
  remark: null
}

const tableData = reactive({
  loading: false,
  list: [], // 表格列表数据
});


const openFlag = ref(false);
const form = ref();
const categoryTableRef = ref()
const assetTableRef = ref()

const formData = reactive({...formDataInit})

const rules = reactive({
  categoryList: {
    required: true,message: '不能为空', trigger: 'blur',
  }
})

const categoryTableValidRules = {
  categoryId: [{
    required: true,message: '不能为空', trigger: 'blur',
  }],
  num: [{
    required: true,message: '不能为空', trigger: 'blur',
  }],
}

const regionEditRender = reactive({
  name: 'VxeTreeSelect',
  options: []
});

function insertCategoryList() {
  formData.categoryList.push({})
}

function reset() {
  Object.assign(applyData, applyDataInit);
  Object.assign(formData, formDataInit);
  tableData.list = [];
}

function open(row) {
  openFlag.value = true;
  reset();
  if (row) {
    api.detail(row).then(response=> {
      Object.assign(applyData, response);
      const resFormData = response.formData;
      if (resFormData) {
        Object.assign(formData, resFormData);
      }

      let categoryList = formData.categoryList;
      if (!categoryList) {
        categoryList = []
      }
      categoryTableRef.value.setList(categoryList)

    })
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
}

function close() {
  openFlag.value = false;
}

function getParams() {
  const apply = { ...applyData };

  apply.applyType = props.applyType;
  apply.applyTypeName = props.applyTypeName;
  let num = 0;
  debugger
  if (formData.applyType === 1) {
    if (formData.categoryList && formData.categoryList.length > 0) {
      num = formData.categoryList.reduce((acc, cur) => {
        return acc + parseInt(cur.num);
      }, 0);
    }
  } else if (formData.applyType === 2) {
    if (formData.assetList && formData.assetList.length > 0) {
      num = formData.assetList.reduce((acc, cur) => {
        return acc + parseInt(cur.num);
      }, 0);
    }
  }
  formData.num = num;
  apply.formData = JSON.stringify(formData);
  return {
    edit: isEdit.value,
    apply: apply
  }
}

function check() {
  return new Promise((resolve, reject) => {
    form.value.validate(async (valid) => {
      if (valid) {
        resolve();
      } else {
        reject();
      }
    });
  })
}

async function handleDeleteCategory(row, index) {
  const $table = categoryTableRef.value;
  if ($table) {
    const type = await VxeUI.modal.confirm('您确定要删除该数据?');
    if (type === 'confirm') {
      formData.categoryList.splice(index, 1);
    }
  }
}

/** 保存 */
function save() {
  check().then(()=> {
    api.save(getParams()).then(response => {
      emit("sub");
      close();
    });
  });
}

function sub() {
  check().then(()=> {
    api.saveAndSub(getParams()).then(response => {
      emit("sub");
      close();
    });
  });

}

onMounted(() => {
});

defineExpose({
  open
})

</script>

